var directives = angular.module('directives', []);
directives.directive("leftmenu", function() {
    return {
        restrict : "AE",
        templateUrl : "/pages/include/menu.html"
    };
});

//表单验证
directives.directive("formValidate", function() {
    return {
        restrict : "A",//节点属性生效
        template: function(iElement, iAttrs){
            var formName = iElement.closest("form").attr("name");
            var inputEle = iElement.children("[ng-model]");
            inputEle.addClass("width-90");
            var target_name = formName+"."+inputEle.attr("name")
            var html = "<div class='form-group'  ng-class=\"{'has-error':(!resestValidate && "+target_name+".$invalid && !"+target_name+".$pristine),'has-success':!"+target_name+".$invalid}\">"+
                "<span class='block input-icon input-icon-right'>"+
                iElement.html()+
                "<i ng-show='!resestValidate && "+target_name+".$invalid && !"+target_name+".$pristine' class='ace-icon fa fa-times-circle'></i>"+
                "<i ng-show='"+target_name+".$valid' class='ace-icon fa fa-check-circle'></i>"+
                "</span>"+
                "</div>";
            return html
        }

    };
});

//单文件上传
directives.directive("singleFile", function() {
    return {
        restrict : "A",//节点属性生效
        link: function(scope,iElement, iAttrs){
            iElement.ace_file_input({
                style:'well',
                btn_choose:'请点击上传图片，不超过1M',
                btn_change:null,
                no_icon:'ace-icon fa fa-cloud-upload',
                droppable:true,
                allowExt:  ['jpg','png'],
                allowMime: ['image/jpg', 'image/jpeg','image/png'],
                thumbnail:'large'	//small | large | fit
            }).on('change', function(){
                //alert($(this).data('ace_input_files'));
                //alert($(this).data('ace_input_method'));
            }).on('file.error.ace', function(event, info) {
                dialog.alert("请选择正确的图片类型,仅支持jpg,png格式的图片!");
                event.preventDefault();
            });

        }

    };
});

//多文件上传
directives.directive("multipleFile", function() {
    return {
        restrict : "A",//节点属性生效
        link: function(scope,iElement, iAttrs){
            iElement.ace_file_input({
                style:'well',
                btn_choose:'请选择文件',
                btn_change:null,
                no_icon:'ace-icon fa fa-cloud-upload',
                droppable:true,
                /*allowExt:  ['jpg'],
                 allowMime: ['image/jpg', 'image/jpeg'],*/
                thumbnail:'small'//large | fit
                ,
                preview_error : function(filename, error_code) {
                    //name of the file that failed
                    //error_code values
                    //1 = 'FILE_LOAD_FAILED',
                    //2 = 'IMAGE_LOAD_FAILED',
                    //3 = 'THUMBNAIL_FAILED'
                    //alert(error_code);
                }

            }).on('change', function(){
                //console.log($(this).data('ace_input_files'));
                //console.log($(this).data('ace_input_method'));

            }).on('file.error.ace', function(event, info) {
                dialog.alert("请选择正确的文件类型");
                event.preventDefault();
            });
//			 $('#addFillDiv').ace_scroll({size:$(window).height()-160});
        }

    };
});

//滚动条
directives.directive("scrollbar", function() {
    return {
        restrict : "A",//节点属性生效
        link: function(scope,iElement, iAttrs){
            var barheight = iElement.attr("scrollbar");

            if(barheight!=undefined && barheight!="" && !isNaN(barheight)){
            }else{
                barheight = $(window).height()-60;
            }
			//alert(barheight);
            iElement.ace_scroll({size:barheight,styleClass:'scroll-chrome'});
        }

    };
});


/*directives.directive('ckeditor', function() {
    return {
        require : '?ngModel',
        link : function(scope, element, attrs, ngModel) {
            var ckeditor = CKEDITOR.replace(element[0], {

            });
            if (!ngModel) {
                return;
            }
            ckeditor.on('instanceReady', function() {
                ckeditor.setData(ngModel.$viewValue);
            });
            ckeditor.on('pasteState', function() {
                scope.$apply(function() {
                    ngModel.$setViewValue(ckeditor.getData());
                });
            });
            ngModel.$render = function(value) {
                ckeditor.setData(ngModel.$viewValue);
            };
        }
    };
});*/



directives.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs, ngModel) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;
            element.bind('change', function(event){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
                //附件预览
                scope.file = (event.srcElement || event.target).files[0];
                //scope.getFile();
            });
        }
    };
}]);

//分页条，待完善
directives.directive("splitpage", function() {
    return {
        restrict : "A",//节点属性生效
        templateUrl: function(iElement, iAttrs){
            return "pages/include/splitPage.html"
        }
    };
});

//分页条，待完善
directives.directive("splitpage2", function() {
    return {
        restrict : "A",//节点属性生效
        templateUrl: function(iElement, iAttrs){
            return "pages/include/splitPage2.html"
        }
    };
});




//监听 ng-repeat循环完成
directives.directive('repeatFinish',function(){
    return {
        link: function(scope,element,attr){
            if(scope.$last == true){
                scope.$eval( attr.repeatFinish )
            }
        }
    }
})

//时间组件，加onChange 类型：yyyy-MM-dd HH:mm:ss
directives.directive("wdatePicker", function() {
    return {
        restrict : "A",//节点属性生效
        link: function(scope,iElement, iAttrs){
            iElement.attr("readonly",true);
            iElement.bind("focus",function(){
                dateFmt =iElement.attr('dateformat');
                if(scope.data!=null&&scope.data.dateFmt!=null){
                    //dateFmt = scope.data.dateFmt;
                }else if(null==dateFmt||""==dateFmt){
                    dateFmt = 'yyyy-MM-dd HH:mm:ss';
                }
                if(scope.date!=null&&scope.date.startDate!=null&&scope.date.endDate!=null){
                    WdatePicker({dateFmt:dateFmt,minDate:scope.date.startDate,maxDate:scope.date.endDate,
                        onpicked:function(){

                            eval("scope."+iElement.attr('ng-model')+"='"+this.value+"'");
                            scope.$apply();
                            this.blur();
                        }})
                }else{
                    WdatePicker({dateFmt:dateFmt,
                        onpicked:function(){
                            eval("scope."+iElement.attr('ng-model')+"='"+this.value+"'");
                            //scope.setParam(iElement.attr("ng-model"),this.value,{target:this});
                            scope.$apply();
                            this.blur();
                        }})
                }

            })
        }
    };
});


//日期组件，加onChange  类型：yyyy-MM-dd
directives.directive("wtimePicker", function() {
    return {
        restrict : "A",//节点属性生效
        link: function(scope,iElement, iAttrs){
            iElement.attr("readonly",true);
            iElement.bind("focus",function(){
                dateFmt =iElement.attr('dateformat');
                if(scope.data!=null&&scope.data.dateFmt!=null){
                    //dateFmt = scope.data.dateFmt;
                }else if(null==dateFmt||""==dateFmt){
                    dateFmt = 'yyyy-MM-dd';
                }
                if(scope.date!=null&&scope.date.startDate!=null&&scope.date.endDate!=null){
                    WdatePicker({dateFmt:dateFmt,minDate:scope.date.startDate,maxDate:scope.date.endDate,
                        onpicked:function(){

                            eval("scope."+iElement.attr('ng-model')+"='"+this.value+"'");
                            scope.$apply();
                            this.blur();
                        }})
                }else{
                    WdatePicker({dateFmt:dateFmt,
                        onpicked:function(){
                            eval("scope."+iElement.attr('ng-model')+"='"+this.value+"'");
                            //scope.setParam(iElement.attr("ng-model"),this.value,{target:this});
                            scope.$apply();
                            this.blur();
                        }})
                }

            })
        }
    };
});

//动态编译HTML 字符串，让HTML字符串里的函数起作用
directives.directive("dyCompile", ["$compile", function($compile) {
    return {
        replace: true,
        restrict: 'EA',
        link: function(scope, elm, iAttrs) {
            var DUMMY_SCOPE = {
                    $destroy: angular.noop
                },
                root = elm,
                childScope,
                destroyChildScope = function() {
                    (childScope || DUMMY_SCOPE).$destroy();
                };

            iAttrs.$observe("html", function(html) {
                if (html) {
                    destroyChildScope();
                    childScope = scope.$new(false);
                    var content = $compile(html)(childScope);
                    root.replaceWith(content);
                    root = content;
                }

                scope.$on("$destroy", destroyChildScope);
            });
        }
    };
}])


